/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package ca.usherbrooke.behaviours.controller.request;

import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
import ca.usherbrooke.agent.WorldUpdaterAgent;
import ca.usherbrooke.behaviours.BasicSubscriberBehaviour;
import ca.usherbrooke.behaviours.world.SubscriptionWorldModel;
import ca.usherbrooke.model.world.IWorldModel;
import ca.usherbrooke.utils.ExceptionTool;

/**
 * @author Cody Stoutenburg
 * 
 */
public class SubscriberWorldModel extends
		BasicSubscriberBehaviour<WorldUpdaterAgent> {

	private static final long serialVersionUID = 1L;

	private static final ACLMessage buildSubscriptionMessage(AID subscribeTo) {
		ACLMessage msg = new ACLMessage(
				SubscriptionWorldModel.SUBSCRIPTION_WORLD_PERFORMATIVE);
		msg.setProtocol(SubscriptionWorldModel.SUBSCRIPTION_WORLD_PROTOCOL);
		msg.setContent(SubscriptionWorldModel.SUBSCRIPTION_WORLD_MESSAGE);
		msg.addReceiver(subscribeTo);

		return msg;
	}

	private static final ACLMessage buildUnsubscriptionMessage(AID subscribeTo) {
		ACLMessage msg = new ACLMessage(
				SubscriptionWorldModel.SUBSCRIPTION_WORLD_PERFORMATIVE);
		msg.setProtocol(SubscriptionWorldModel.SUBSCRIPTION_WORLD_PROTOCOL);
		msg.setContent(SubscriptionWorldModel.UNSUBSCRIPTION_WORLD_MESSAGE);
		msg.addReceiver(subscribeTo);

		return msg;
	}

	private final AID subscribeTo;

	/**
	 * @param agent
	 * @param msg
	 */
	public SubscriberWorldModel(WorldUpdaterAgent agent, AID subscribeTo) {
		super(agent, buildSubscriptionMessage(subscribeTo));
		this.subscribeTo = subscribeTo;
	}

	@Override
	protected void messageReceived(ACLMessage msg) {
		try {
			IWorldModel world = (IWorldModel) msg.getContentObject();
			this.getAgent().setWorld(world);
		} catch (UnreadableException ex) {
			ExceptionTool.showError(ex);
		}
	}

	public void unsubscribe() {
		this.getAgent().send(buildUnsubscriptionMessage(subscribeTo));
	}
}
